package com.s63.ssm.controller;

import com.s63.ssm.entity.Page;
import com.s63.ssm.entity.SysUser;
import com.s63.ssm.service.RoleService;
import com.s63.ssm.service.UserService;
import com.s63.ssm.singleton.ConfigManager;
import com.s63.ssm.valid.AddGroup;
import com.s63.ssm.valid.UpdateGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping("/users")
@Controller
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "user/login";
    }

    @GetMapping("/login")
    public String login() {
        return "user/login";
    }

    @PostMapping("/login")
    public String login(String account, String password, HttpSession session, Model model) throws Exception {
        SysUser loginUser = userService.getLogin(account, password);
        session.setAttribute("loginUser", loginUser);
        return "redirect:/users/list";
    }

    @GetMapping("/list2")
    @ResponseBody
    public Page<SysUser> list(SysUser user, Page<SysUser> page) {
        userService.getByRealNameAndRoleIdPage(user.getRealName(), user.getRoleId(), page);
        return page;
    }

    @RequestMapping("/list")
    public String list(Page<SysUser> page, String realName, Integer roleId, Model model) {
        userService.getByRealNameAndRoleIdPage(realName, roleId, page);
        model.addAttribute("page", page);
        model.addAttribute("realName", realName);
        model.addAttribute("roleId", roleId);
        model.addAttribute("uploadHost", ConfigManager.getInstance().getValue("upload.host"));
        return "user/index";
    }

    @GetMapping("/add")
    public String toAdd(Model model) {
        model.addAttribute("command", new SysUser());
//        model.addAttribute("roleList", roleService.getAll());
        return "user/add";
    }

    @PostMapping(value = "/add2")
    @ResponseBody
    public boolean add2(@RequestBody SysUser user) {
        userService.add(user);
        return true;
    }

    @PostMapping("/add")
    public String add(@Validated(AddGroup.class) @ModelAttribute("command") SysUser user,
                      BindingResult bindingResult,
                      Model model, @RequestParam("uploadFiles") MultipartFile[] uploadFiles) throws IOException {
        if (uploadFiles[0].getSize() == 0) {
            bindingResult.addError(new FieldError("command", "idPicPath", "id文件不能为空"));
        }
        if (uploadFiles[1].getSize() == 0) {
            bindingResult.addError(new FieldError("command", "workPicPath", "work文件不能为空"));
        }
        if (uploadFiles != null && uploadFiles.length == 2) {
            if (uploadFiles[0].getSize() > 1024 * 1024) {
                bindingResult.addError(new FieldError("command", "idPicPath", "idPicPath文件太大"));
            }
            if (uploadFiles[1].getSize() > 1024 * 1024) {
                bindingResult.addError(new FieldError("command", "workPicPath", "workPicPath文件太大"));
            }
        }
        if (bindingResult.hasErrors()) {
            return "user/add";
        }
        // 保存上传的文件
        if (uploadFiles != null && uploadFiles.length == 2) {
            if (uploadFiles[0].getSize() > 1024 * 1024) {

            }
            user.setIdPicPath(saveFile(uploadFiles[0]));
            user.setWorkPicPath(saveFile(uploadFiles[1]));
        }
        userService.add(user);
        // 重定向到控制器
        return "redirect:/users/list";
//        return list(new Page<>(), null, null, model);
    }

    private String saveFile(MultipartFile idPicPathFile) throws IOException {
        if (idPicPathFile == null || idPicPathFile.getSize() == 0) return "";
        // 重命名文件
        String filename = idPicPathFile.getOriginalFilename();
        filename = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));
        // 保存上传文件
        idPicPathFile.transferTo(new File("c:\\tmp", filename));
        return filename;
    }

    @GetMapping("/toUpdate")
    public String toUpdate(Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
//        model.addAttribute("roleList", roleService.getAll());
        model.addAttribute("uploadHost", ConfigManager.getInstance().getValue("upload.host"));
        return "user/update";
    }

    @GetMapping("/toRestUpdate/{id}")
    public String toRestUpdate(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
        model.addAttribute("roleList", roleService.getAll());
        model.addAttribute("uploadHost", ConfigManager.getInstance().getValue("upload.host"));
        return "user/update";
    }

    @PostMapping("/update")
    public String update(@Validated(UpdateGroup.class) @ModelAttribute("user") SysUser user, BindingResult bindingResult, MultipartFile idPicPathFile) throws IOException {
        if (bindingResult.hasErrors()) {
            return "user/update";
        }
        String filename = this.saveFile(idPicPathFile);
        user.setIdPicPath(filename);
        userService.update(user);
        return "redirect:/users/list";
    }

    @GetMapping("/del")
    public String del(Integer id) {
        userService.del(id);
        return "redirect:/users/list";
    }

    @GetMapping("/{id}/restDel")
    public String restDel(@PathVariable Integer id) {
        userService.del(id);
        return "redirect:/users/list";
    }


    @GetMapping(value = "/userExist")
    @ResponseBody
    public Object userExist(String account) {
        SysUser user = userService.getByAccount(account);
        Map<String, Object> map = new HashMap<>();
        map.put("found", user != null);
        map.put("msg", user == null ? "可以使用" : "已经存在");
        return map;
    }

    @GetMapping(value = "/view")
    @ResponseBody
    public SysUser view(Integer id) {
        return userService.getById(id);
    }

    @GetMapping(value = "/view2")
    public String view2(Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
        return "user/view";
    }

    @GetMapping(value = "/ajaxDel")
    @ResponseBody
    public boolean ajaxDel(Integer id) {
        return userService.del(id) == 1;
    }
   /* // 局部异常处理
    @ExceptionHandler(value = {Exception.class})
    public String handlerException(Exception e, Model model) {
        model.addAttribute("exception", e);
        return "error";
    }*/
}
